#include "idreader.h"
#include <qnetworkaccessmanager.h>
#include <qnetworkreply.h>
#include <qjsonobject.h>
#include <QJsonDocument>
#include <qtimer.h>
#include "formatter.h"
#include "settings.h"

IDReader::IDReader(QObject *parent)
    : QObject{parent},
    manager(new QNetworkAccessManager(this)),
    timer(new QTimer(this))
{
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));
    connect(timer, SIGNAL(timeout()), this, SLOT(readCard()));
    timer->start(1000);
}

void IDReader::readCard()
{
    QNetworkRequest request(Settings::Singleton().cardEndPoint());
    manager->get(request);
}

void IDReader::onNetworkReply(QNetworkReply *reply)
{
    QByteArray content = reply->readAll();
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(content, &err);
    if (err.error != QJsonParseError::ParseError::NoError) {
        qCritical() << "Json parse failed: " << err.errorString();
        return;
    }

    QJsonObject resp = doc.object();
    const int flag = resp.value("resultFlag").toInt(-1);
    if (flag != 0) {
        return;
    }

    QJsonObject idc = resp.value("resultContent").toObject();
    if (idc.isEmpty()) {
        qCritical() << "Empty id content: " << idc;
        return;
    }

    const Settings &s = Settings::Singleton();
    QJsonObject json;
    json.insert("PatientName", idc.value("partyName"));
    json.insert("PatientBirthDate", idc.value("bornDay"));
    const int gender = idc.value("gender").toInt(-1);
    QString sex = (gender == 1 ? "M" : (gender == 0 ? "F" : "O"));
    json.insert("PatientSex", sex);
    json.insert("PatientID", idc.value("certNumber"));
    json.insert("RequestedProcedureDescription", "胸部正位");
    json.insert("RequestedProcedureID", "RP1234");

    QJsonObject seq;
    seq.insert("Modality", s.cardModality());
    seq.insert("ScheduledStationAETitle", s.cardAet());
    seq.insert("ScheduledProcedureStepDescription", "胸部正位");
    seq.insert("ScheduledProcedureStepID", "SPD1234");
    seq.insert("ScheduledProcedureStepStartDate", QDate::currentDate().toString("yyyyMMdd"));
    seq.insert("ScheduledProcedureStepStartTime", QTime::currentTime().toString("HHmmss"));

    json.insert("ScheduledProcedureStepSequence", seq);

    Formatter::Singleton().processJson(json);
    reply->deleteLater();
}
